package com.whsr.readservice.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whsr.readservice.dao.ArticleMapper;
import com.whsr.readservice.dao.ChapterMapper;
import com.whsr.readservice.enums.DownBookEnum;
import com.whsr.readservice.util.HttpClientUtils;
import com.whsr.readservice.util.InterfaceUtil;
import com.whsr.readservice.util.ResultUtil;
import com.whsr.readservice.vo.Article;
import com.whsr.readservice.vo.Chapter;
import com.whsr.readservice.vo.JobBatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ChapterService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ChapterMapper chapterMapper;

    @Autowired
    private DownBookMaintainService downBookMaintainService;


    public JobBatch insertChapters(JobBatch jobBatch){
        List<Integer> bookIds = downBookMaintainService.getBookIdsBystatus(DownBookEnum.WAIT_CHAPTER.getCode());
        Map<String, Object> param = new HashMap<>();
        List<Chapter> chapters = new ArrayList<>();
        List<Integer> updatebookIds = new ArrayList<>();
        Integer complateNum = 0;
        Integer failNum = 0;
        for (Integer bookId: bookIds) {
            Article article = articleMapper.selectArticleByBookId(bookId);
            if(article != null && article.getChapterCount() != null){
                chapterMapper.deleteByBookId(bookId);
                Integer ChapterCount = article.getChapterCount();
                Integer noChargeCount = ChapterCount * 30 / 100;
                param.put("bk_id", bookId);
                param.put("start", 0);
                param.put("end", ChapterCount);
                JSONObject json = HttpClientUtils.httpPost(InterfaceUtil.urls[1], param);
                if(json == null || json.getInteger("code") != 200){
                    failNum++;
                    continue;
                }
                JSONArray jsonArray = json.getJSONArray("chapters");
                for(int i = 0; i < jsonArray.size(); i++){
                    Chapter chapter = new Chapter();
                    if ( (i+1) <= noChargeCount ) {
                        chapter.setChCharge(0);
                    } else {
                        chapter.setChCharge(1);
                    }
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    chapter.setChId(Integer.valueOf(jsonObject.getString("ch_id")));
                    chapter.setChName(jsonObject.getString("ch_name"));
                    chapter.setChVip(Integer.valueOf(jsonObject.getString("ch_vip")));
                    chapter.setChIndex(jsonObject.getInteger("ch_index") == null ? 0 : jsonObject.getInteger("ch_index"));
                    chapter.setBookId(bookId);
                    chapters.add(chapter);
                }
                if(chapters != null){
                    try{
                        chapterMapper.insertChapters(chapters);
                        updatebookIds.add(bookId);
                        complateNum += chapters.size();
                    } catch (Exception e){
                        failNum += chapters.size();
                        updatebookIds.remove(bookId);
                        continue;
                    }
                    chapters.clear();
                }
            }
        }
        if(updatebookIds.size() > 0){
            int forNum = (updatebookIds.size() % InterfaceUtil.MAX_COUNT) > 0 ? (updatebookIds.size() / InterfaceUtil.MAX_COUNT) + 1 : (updatebookIds.size() / InterfaceUtil.MAX_COUNT);
            for (int i = 0; i < forNum; i++){
                List<Integer> newUpdatebookIds = null;
                if(i != forNum -1){
                    newUpdatebookIds = updatebookIds.subList(i*InterfaceUtil.MAX_COUNT, (i+1)*InterfaceUtil.MAX_COUNT);
                } else {
                    newUpdatebookIds = updatebookIds.subList(i*InterfaceUtil.MAX_COUNT, updatebookIds.size());
                }
                if(newUpdatebookIds != null && newUpdatebookIds.size() > 0){
                    try{
                        downBookMaintainService.updateDownBookMaintains(newUpdatebookIds, DownBookEnum.WAIT_CONTENT.getCode());
                    } catch (Exception e){
                        continue;
                    }
                }
            }
        }
        jobBatch.setCompleteChpArtNum(updatebookIds.size());
        jobBatch.setFailChpArtNum(bookIds.size() - updatebookIds.size());
        jobBatch.setCompleteChpNum(complateNum);
        jobBatch.setFailChpNum(failNum);
        return jobBatch;
    }

    public PageInfo<Chapter> getChaptersByBookId(Integer bookId, Integer pageNo, Integer pageSize){
        PageHelper.startPage(pageNo, pageSize);
        List<Chapter> list = chapterMapper.selectChaptersByBookId(bookId);
        PageInfo<Chapter> pageInfo = new PageInfo<Chapter>(list);
        return pageInfo;
    }

    public Map<String, Object> getChaptersByApp(Integer bookId) {
        Map<String, Object> root = new HashMap<>();
        List<Map<String, Object>> chapterMaps = new ArrayList();
        List<Chapter> chapters = chapterMapper.selectChaptersByApp(bookId);
        for(Chapter chapter : chapters){
            Integer chId = chapter.getChId();
            Map<String, Object> other = new HashMap();
            other.put("chId", chapter.getChId());
            other.put("chName", chapter.getChName());
            other.put("bookId", chapter.getBookId());
            other.put("chCharge", chapter.getChCharge());

            other.put("preChId", 0);
            other.put("preChCharge", 0);
            other.put("nextChId", 0);
            other.put("nextChCharge", 0);
            List<Chapter> chapterPreNext = this.getPreNextChIdByByBookIdAndChId(bookId,chId);
            Chapter chapterPre = null;
            Chapter chapterNext = null;
            for(int i = 0; i < chapterPreNext.size(); i++){
                if(i == 0 && !chapterPreNext.get(i).getChId().equals(chId)){
                    chapterPre = chapterPreNext.get(i);
                } else if(i == chapterPreNext.size() - 1 && !chapterPreNext.get(i).getChId().equals(chId)){
                    chapterNext = chapterPreNext.get(i);
                }
            }
            if(chapterPre != null){
                other.put("preChId", chapterPre.getChId());
                other.put("preChCharge", chapterPre.getChCharge());
            }
            if(chapterNext != null){
                other.put("nextChId", chapterNext.getChId());
                other.put("nextChCharge", chapterNext.getChCharge());
            }
            chapterMaps.add(other);
        }
        root.put("ChpterList", chapterMaps == null ? new ArrayList<Map<String, Object>>() : chapterMaps);
        return ResultUtil.getResultBySuccess(root);
    }

    public List<Chapter> getChaptersByNotContent() {
        return chapterMapper.selectChaptersByNotContent();
    }

    public List<Chapter> getPreNextChIdByByBookIdAndChId(Integer bookId, Integer chId) {
        return chapterMapper.selectPreNextChIdByByBookIdAndChId(bookId, chId);
    }

    public Chapter getPreChIdByByBookIdAndChId(Integer bookId, Integer chId) {
        return chapterMapper.selectPreChIdByByBookIdAndChId(bookId, chId);
    }
}
